//
//  UIImage+CLExtension.m
//
//  Created by danal on 3/2/12.
//  Copyright (c) 2012 . All rights reserved.
//

#import "UIImage+CLExtension.h"

@implementation UIImage (CLExtension)

///  image缩放 newSize
- (UIImage *)resizeToSize:(CGSize)newSize {
    
    UIGraphicsBeginImageContext(newSize);
    CGContextRef c = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(c, 0, newSize.height);
    CGContextScaleCTM(c, 1, -1);
    CGRect rect = CGRectMake(0, 0, newSize.width, newSize.height);
    CGContextDrawImage(c, rect, self.CGImage);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

/// image长宽等比缩放 newSize
- (UIImage *)scaleToSize:(CGSize)newSize {
    float max = MAX(self.size.width, self.size.height);
    if (max > MAX(newSize.width, newSize.height)) {
        float factor = MAX(newSize.width, newSize.height)/max;
        return [self scaleByFactor:factor];
    }
    return self;
}

/// image 比例缩放
- (UIImage *)scaleByFactor:(float)scaleBy
{
    UIImage *image = self;
    CGSize size = CGSizeMake((image.size.width * scaleBy), (image.size.height * scaleBy));
    
    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    transform = CGAffineTransformScale(transform, scaleBy, scaleBy);
    CGContextConcatCTM(context, transform);
    
    // Draw the image into the transformed context and return the image
    [image drawAtPoint:CGPointMake(0.0f, 0.0f)];
    UIImage *newimg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newimg;
}

/// 把 image 调整为可拉伸
- (UIImage *)resizableWithLeftCap:(CGFloat)dx topCap:(CGFloat)dy width:(CGFloat)w height:(CGFloat)h
{
    UIImage *image = nil;
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 5.0f) {
        image = [self stretchableImageWithLeftCapWidth:dx topCapHeight:dy];
    } else {
        image = [self resizableImageWithCapInsets:UIEdgeInsetsMake(dx, dy, self.size.width - dx + w, self.size.height - dy + h)];
    }
    return image;
}

/// png格式转换为jpg格式
- (UIImage *)PNG2JPG {
    NSData *data = UIImageJPEGRepresentation(self, .8f);
    return [UIImage imageWithData:data];
}


/// Always draw the original image, without treating it as a template.
- (UIImage *)renderOriginal {
    return [self imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}


@end
